package zsh.core;

import com.alibaba.fastjson2.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import zsh.config.HasUserName;
import zsh.domain.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;

@Component
public class MyInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取session
        HttpSession session = request.getSession();
        User LoginUser = (User) session.getAttribute("LoginUser");
        if (LoginUser == null) {
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JSONObject.toJSONString(Result.error(401,"请先登录")));
            return false;
        }
        //获取要执行的方法
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            HasUserName hasUserName = method.getAnnotation(HasUserName.class);
            if(hasUserName != null) {
                //从session中获取登录用户的角色
                if (LoginUser.getUsername().equals(hasUserName.role())){
                    return true;
                }
                else {
                    response.setContentType("application/json;charset=utf-8");
                    response.getWriter().write(JSONObject.toJSONString(Result.error(403,"没有操作权限")));
                }
            }
        }

        return true;
    }
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle");
    }
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion");
    }
}
